package com.webchat.aigc.controller;


import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.bean.APIResponseBeanUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/aigc-service/springai")
public class SpringAiChatTestController {


    @Autowired
    private ChatModel deepSeekChatModel;

    @Autowired
    private HttpServletResponse response;


    @GetMapping("/deepseek/chat")
    public APIResponseBean<String> chat(@RequestParam String query) {

        String content = ChatClient.builder(deepSeekChatModel).build().prompt()
                .system("你是chat4j课程ai学习助手，你叫七七。")
                .user(query)
                .call()
                .content();

        return APIResponseBeanUtil.success(content);
    }


    @GetMapping(value = "/deepseek/chat/stream" , produces = "text/event-stream;charset=UTF-8")
    public Flux<String> chatStream(@RequestParam String query) {
        response.setCharacterEncoding("UTF-8");
        var prompt = new Prompt(new SystemMessage("你是chat4j课程ai学习助手，你叫七七。"),
                                new UserMessage(query));
        return deepSeekChatModel.stream(prompt).map(resp -> {
            Generation generation = resp.getResult();
            if (generation != null &&
                generation.getOutput() != null) {
                return generation.getOutput().getText();
            }
            return "";
        }).concatWithValues("===finished!===");
    }
}
